package com.open.basic.spring;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author system
 * @Date 2023/12/3 14:34
 * @description bean后置处理器
 */
@Slf4j
@Component
public class BasicBeanPostProcess implements BeanPostProcessor {

    private static final Map<String, Date> DATE_MAP = new HashMap<>();

    @PostConstruct
    public void init() {
        log.info("BasicBeanPostProcess init");
    }
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        log.info("load bean:{} class:{}", beanName, bean.getClass().getName());
        // DATE_MAP.put(beanName, new Date());
        return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        //  DATE_MAP.remove(beanName) 会NPE
        // log.info("loaded beanName:{}, cos time:{}", beanName,System.currentTimeMillis() - DATE_MAP.remove(beanName).getTime());
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}
